﻿using System;
using System.Collections;
using System.Configuration;
using System.Data;
using System.Linq;
using System.Web;
using System.Web.Security;
using System.Web.UI;
using System.Web.UI.HtmlControls;
using System.Web.UI.WebControls;
using System.Web.UI.WebControls.WebParts;
using System.Xml.Linq;
using System.Data.OleDb;

public partial class Checkout : System.Web.UI.Page
{
    private CartData cart;

    protected void Page_Load(object sender, EventArgs e)
    {
        if (!IsPostBack)
        {
            if (!Master.CheckLogin())
            {
                Server.Transfer("Login.aspx?returnTo=Checkout.aspx");
            }
            else if (Session["ShippingData"] == null) // Get shipping info first if not already in session
            {
                Server.Transfer("Shipping.aspx");
            }
            else
            {
                ShippingData shipping = (ShippingData)Session["ShippingData"];
                // Require user to re-enter shipping info each time
                //Session.Remove("ShippingData"); 
                lblName.Text = shipping.FullName;
                lblStreet1.Text = shipping.Street1;
                lblStreet2.Text = shipping.Street2;
                lblCity.Text = shipping.City;
                lblState.Text = shipping.State;
                lblZip.Text = shipping.Zip;

                this.cart = CartData.getCartFromSession(Page);

                //Bind the DataTable from the CartData object to the DataList
                cartGridView.DataSource = this.cart.getCartTable();
                cartGridView.DataBind();

                // Allow the user to see total price, edit cart, and place order
                // if the cart isn't empty.
                bool completeOrder = cartGridView.Rows.Count > 0;
                lblLabelTotal.Visible = completeOrder;
                lblTotal.Visible = completeOrder;
                cmdEditCart.Visible = completeOrder;
                cmdPlaceOrder.Visible = completeOrder;

                lblTotal.Text = '$'+cart.getTotal().ToString();
            }
        }
    }
    protected void cmdEditCart_Click(object sender, EventArgs e)
    {
        Response.Redirect("ShoppingCart.aspx");
    }
    protected void cmdEditShip_Click(object sender, EventArgs e)
    {
        Server.Transfer("Shipping.aspx");
    }
    protected void cmdPlaceOrder_Click(object sender, EventArgs e)
    {
        // Create a new order record in Order table
        int orderId = createOrderInDB((string)Session["userID"], (ShippingData)Session["ShippingData"]);

        // Add each item from cart to OrderItems table
        this.cart = CartData.getCartFromSession(Page);
        DataTable orderedItems = cart.getCartTable();
        foreach (DataRow i in orderedItems.Rows)
        {
            addItemToOrder(orderId, i);
        }

        // Clear the cart
        this.cart.reset();

        // Show thank you page
        Response.Redirect("ThankYou.aspx?orderId=" + orderId.ToString());
    }
    protected void cmdContShopping_Click(object sender, EventArgs e)
    {
        Response.Redirect("Default.aspx");
    }
    private int createOrderInDB(string userId, ShippingData address)
    {
        // Define DB objects
        string connectionString = ConfigurationManager.ConnectionStrings["BooksDataSet"].ConnectionString;

        string insertSQL = "INSERT INTO Orders (";
        insertSQL += "UserName, FirstName, LastName, Address, Address2,";
        insertSQL += "City, State, Zip, TransactionDate)";
        insertSQL += "VALUES (";
        insertSQL += "@UserName, @FirstName, @LastName, @Address, @Address2,";
        insertSQL += "@City, @State, @Zip, @TransactionDate)";

        OleDbConnection conn = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand(insertSQL, conn);

        cmd.Parameters.AddWithValue("@UserName", userId);
        cmd.Parameters.AddWithValue("@FirstName", address.FirstName);
        cmd.Parameters.AddWithValue("@LastName", address.LastName);
        cmd.Parameters.AddWithValue("@Address", address.Street1);
        cmd.Parameters.AddWithValue("@Address2", address.Street2);
        cmd.Parameters.AddWithValue("@City", address.City);
        cmd.Parameters.AddWithValue("@State", address.State);
        cmd.Parameters.AddWithValue("@Zip", address.Zip);
        cmd.Parameters.AddWithValue("@TransactionDate", DateTime.Now.Date);

        int orderId = 0;
        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
            cmd.CommandText = "SELECT @@Identity"; // Get the new OrderID
            orderId = (int)cmd.ExecuteScalar();
        }
        catch (Exception err)
        {
            lblStatus.Text = "Error creating order record.";
            lblStatus.Text += err.Message;
        }
        finally
        {
            conn.Close();
        }

        return orderId;
    }
    private void addItemToOrder(int orderId, DataRow item)
    {
        // Define DB objects
        string connectionString = ConfigurationManager.ConnectionStrings["BooksDataSet"].ConnectionString;

        string insertSQL = "INSERT INTO OrderItems (";
        insertSQL += "OrderID, ISBN, Quantity, Price)";
        insertSQL += "VALUES (";
        insertSQL += "@OrderID, @ISBN, @Quantity, @Price)";

        OleDbConnection conn = new OleDbConnection(connectionString);
        OleDbCommand cmd = new OleDbCommand(insertSQL, conn);

        cmd.Parameters.AddWithValue("@OrderID", orderId);
        cmd.Parameters.AddWithValue("@ISBN", item["ISBN"]);
        cmd.Parameters.AddWithValue("@ISBN", item["Quantity"]);
        cmd.Parameters.AddWithValue("@ISBN", item["Price"]);

        try
        {
            conn.Open();
            cmd.ExecuteNonQuery();
        }
        catch (Exception err)
        {
            lblStatus.Text = "Error creating order record.";
            lblStatus.Text += err.Message;
        }
        finally
        {
            conn.Close();
        }
    }
}
